import { defineStore } from 'pinia'
import { userApi } from '@/api'
import config from '@/config'

export const useUserStore = defineStore('user', {
  state: () => ({
    // 用户信息
    userInfo: null,
    // 登录状态
    isLoggedIn: false,
    // token
    token: localStorage.getItem(config.storage.token) || null,
    // 加载状态
    loading: false
  }),

  getters: {
    // 获取用户昵称
    nickname: (state) => state.userInfo?.nickname || state.userInfo?.username || '未登录',

    // 获取用户头像
    avatar: (state) => state.userInfo?.avatar || '',

    // 是否已登录
    isAuthenticated: (state) => !!state.token && state.isLoggedIn,

    // 用户ID
    userId: (state) => state.userInfo?.id || null
  },

  actions: {
    // 用户登录
    async login(loginData) {
      try {
        this.loading = true
        const response = await userApi.login(loginData)

        if (response.code === 200) {
          this.token = response.data.token
          this.userInfo = response.data.userInfo
          this.isLoggedIn = true

          // 保存到本地存储
          localStorage.setItem(config.storage.token, this.token)
          localStorage.setItem(config.storage.userInfo, JSON.stringify(this.userInfo))

          return { success: true, message: '登录成功' }
        } else {
          return { success: false, message: response.message || '登录失败' }
        }
      } catch (error) {
        console.error('登录失败:', error)
        return { success: false, message: error.message || '登录失败' }
      } finally {
        this.loading = false
      }
    },

    // 用户注册
    async register(registerData) {
      try {
        this.loading = true
        const response = await userApi.register(registerData)

        if (response.code === 200) {
          return { success: true, message: '注册成功' }
        } else {
          return { success: false, message: response.message || '注册失败' }
        }
      } catch (error) {
        console.error('注册失败:', error)
        return { success: false, message: error.message || '注册失败' }
      } finally {
        this.loading = false
      }
    },

    // 获取用户信息
    async getUserInfo() {
      try {
        if (!this.token) return

        const response = await userApi.getUserInfo()

        if (response.code === 200) {
          this.userInfo = response.data
          this.isLoggedIn = true
          localStorage.setItem(config.storage.userInfo, JSON.stringify(this.userInfo))
        }
      } catch (error) {
        console.error('获取用户信息失败:', error)
        this.logout()
      }
    },

    // 更新用户信息
    async updateUserInfo(userData) {
      try {
        this.loading = true
        const response = await userApi.updateUserInfo(userData)

        if (response.code === 200) {
          this.userInfo = { ...this.userInfo, ...response.data }
          localStorage.setItem(config.storage.userInfo, JSON.stringify(this.userInfo))
          return { success: true, message: '更新成功' }
        } else {
          return { success: false, message: response.message || '更新失败' }
        }
      } catch (error) {
        console.error('更新用户信息失败:', error)
        return { success: false, message: error.message || '更新失败' }
      } finally {
        this.loading = false
      }
    },

    // 用户登出
    async logout() {
      try {
        if (this.token) {
          await userApi.logout()
        }
      } catch (error) {
        console.error('登出失败:', error)
      } finally {
        // 清除状态
        this.userInfo = null
        this.isLoggedIn = false
        this.token = null

        // 清除本地存储
        localStorage.removeItem(config.storage.token)
        localStorage.removeItem(config.storage.userInfo)
      }
    },

    // 初始化用户状态
    initUserState() {
      const token = localStorage.getItem(config.storage.token)
      const userInfo = localStorage.getItem(config.storage.userInfo)

      if (token && userInfo) {
        this.token = token
        this.userInfo = JSON.parse(userInfo)
        this.isLoggedIn = true
        // 验证token有效性
        this.getUserInfo()
      }
    }
  }
})
